var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('./logger');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');

var routes = require('./routes/index');
var users = require('./routes/users');
var article = require('./routes/article');
var web = require('./routes/web');
var ad = require('./routes/ad');
var talk = require('./routes/talk');
var notice = require('./routes/notice');
var ueditor = require('./routes/ueditor');

var config = require('./config');
var db = require('./database');

var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer({dest: config.ueditorFileDir}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.static(path.join(__dirname, 'uploads')));
app.use(function (req,res,next) {
    if(req.method == 'POST'){
        logger.access(req.method,req.url,req.body);
    }else{
        logger.access(req.method,req.url)
    }
   next();
});

app.use('/', routes);

// session check
app.use(function (req, res, next) {
    var sessionId = req.cookies[config.sessionName];
    if (!sessionId) {
        res.json({status: -1, error: config.ErrorStr.needLogin});
    } else {
        db.getSession(req, sessionId, function (err, session) {
            if (err) {
                logger.error(err.stack);
                res.json({status: -1, error: err.message});
            } else {
                if (session) {
                    db.updateSession(sessionId, function (err) {
                        if (err) {
                            logger.error(err.stack);
                            res.json({status: 0, error: err.message});
                        } else {
                            req.sess = session;
                            res.cookie(config.sessionName,sessionId,{expires: new Date(Date.now() + config.sessionTimeout),maxAge: config.sessionTimeout, httpOnly: false});
                            next();
                        }
                    });
                } else {
                    res.json({status:-1, error: config.ErrorStr.needLogin});
                }
            }
        });
    }
});

app.use('/users', users);
app.use('/article', article);
app.use('/web', web);
app.use('/ad', ad);
app.use('/talk', talk);
app.use('/notice', notice);
app.use('/files', ueditor);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
